import rsa
import base64


def test_rsa():
    # 生成密钥
    (pub, pri) = rsa.newkeys(1024)

    pubstr = pub.save_pkcs1().decode()
    pristr = pri.save_pkcs1().decode()

    print(pubstr)
    print(pristr)

    # 加载已存在的字符串密钥
    pub2 = rsa.PublicKey.load_pkcs1(pubstr)
    pri2 = rsa.PrivateKey.load_pkcs1(pristr)

    msg = "杨春波"

    # 加密
    msgcry = rsa.encrypt(msg.encode(), pub2)

    # 解密
    msg2 = rsa.decrypt(msgcry, pri).decode()

    print(msg2)

    # 签名
    msgsign = rsa.sign(msg.encode(), pri2, "MD5")

    ss = base64.b64encode(msgsign)
    print(ss.decode())


    # 验签
    try:
        sisi = base64.b64decode(ss)

        msgw = "杨春波"
        rsa.verify(msgw.encode(), sisi, pub)
        rsa.verify(msgw.encode(), msgsign, pub)
        print("OK")
    except (Exception,):
        print("Wrong")
